Skip to content

fix(playback): select a playable audio track instead of re-encoding - #151

Merged
JonahMMay merged 3 commits into
mainfrom
fix/select-playable-audio-track
Jul 30, 2026
Merged

JonahMMay merged 3 commits into
mainfrom
fix/select-playable-audio-track

Conversation

@JonahMMay

@JonahMMay JonahMMay commented Jul 30, 2026 •

Copy link
Copy Markdown

Three related audio fixes, all pointing the same way: prefer choosing the right track over re-encoding the wrong one.

Selecting a playable track

adjustPlaybackForSelectedAudio promoted direct play → remux when the selected track's codec was undecodable, then re-encoded that track:

if !audioSupported {
    return playback.PlayRemux, true   // ← re-encode the TrueHD
}

On the file under test that meant a lossless TrueHD 7.1 → AAC encode and a stereo downmix, while the same file carried an unused AC-3 5.1 companion in the same language:

# codec layout ch lang
0 truehd 7.1 Atmos 8 en
1 dts DTS-HD MA 7.1 8 en
2 ac3 5.1(side) 6 en
3,4 ac3 stereo 2 en

Copying track 2 beats re-encoding track 0 on every axis: no CPU, no quality loss, and 5.1 survives instead of collapsing to stereo.

SelectClientPlayableAudioTrack prefers, strongest first: codecs the client claims → the originally selected language → most channels within the declared ceiling → lowest index for determinism. Re-encoding stays the fallback when nothing qualifies.

It never overrides an instruction. An explicit audio_track_index is the user's choice, and silently playing different audio than they asked for is worse than re-encoding what they picked — so re-selection only fills in for a default the client cannot decode. Two existing tests (ExplicitDirectPromotesSelectedAudio…, AutoDirectIgnoresApplePreserveFlag…) caught an earlier version of this that did override an explicit selection; the guard now keys off whether audio_track_index was sent at all.

AC-3 family copies on a plain claim

#148 required declared sink passthrough before copying AC-3/E-AC-3 into MP4. That was over-restrictive — Samsung reports AC-3 on all models and E-AC-3 on 2018+, Apple handles both — so a plain codecs_audio claim is evidence enough. The old gate forced needless re-encodes, including of the very companion track the selector now picks.

DTS and TrueHD stay evidence-gated: Tizen reports no DTS decode, and TrueHD in MP4 is unsupported essentially everywhere.

E-AC-3 is never an encode target

Tizen accepts E-AC-3 for direct play but not for transcode. A source E-AC-3 track still passes through untouched via the copy path — that's the direct-play route — but an eac3 target now emits AC-3: same channel layout, broader hardware decode, and no risk of silent audio on precisely the devices that asked for surround.

Test recalibration

Two of my own tests from #148/#149 asserted the over-restrictive AC-3 behaviour. They're recalibrated rather than worked around, with DTS standing in for the fragile set.

internal/playback fully green; api, middleware, proxy, jellycompat green. go vet, gofmt, misspell clean. The single internal/api/handlers failure (TestHandleReplanPlaybackV3SeekFailureRecoveryNeverChangesMediaVersion) is pre-existing on main.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Improvements
    • Automatically picks the best compatible audio track when the initially selected one can’t be decoded, factoring codec support, language preference, channel limits, and deterministic tie-breaking.
    • Enhances AC-3 / E-AC-3 handling to avoid E-AC-3 as an encode target while still allowing direct copy when appropriate.
    • Refines MP4 remux safety so fragile codecs are converted unless clear passthrough support is indicated.
  • Bug Fixes
    • Prevents sessions from starting with an audio track the client can’t play.
    • Improves codec alias recognition and remux/transcode decisions for DTS/TrueHD and related variants.

Three related audio fixes, all pointing the same way: prefer choosing the
right track over re-encoding the wrong one.

Selecting a playable track

  adjustPlaybackForSelectedAudio promoted direct play to remux when the
  selected track's codec was undecodable, then re-encoded that track. On a
  Blu-ray remux whose default is TrueHD 7.1 that meant a lossless->AAC
  encode and a stereo downmix, while the same file carried an AC-3 5.1
  companion in the same language sitting unused. Copying the companion beats
  re-encoding on every axis: no CPU, no quality loss, and surround survives.

  SelectClientPlayableAudioTrack picks the best decodable track, preferring
  claimed codecs, then the originally selected language, then the most
  channels within the client's declared ceiling, then lowest index for
  determinism. Re-encoding remains the fallback when nothing qualifies.

  It never overrides an instruction. An explicit audio_track_index is the
  user's choice, and silently playing different audio than they asked for is
  worse than re-encoding what they picked -- so re-selection only fills in
  for a default the client cannot decode. Two existing tests caught an
  earlier version of this that did override an explicit selection; the guard
  keys off whether audio_track_index was sent at all.

AC-3 family copies on a plain claim

  #148 required declared sink passthrough before copying AC-3/E-AC-3 into
  MP4. That was over-restrictive: Samsung reports AC-3 on all models and
  E-AC-3 on 2018+, and Apple platforms handle both, so a plain codecs_audio
  claim is evidence enough and the gate only forced needless re-encodes --
  including of the very companion track the selector now picks. DTS and
  TrueHD stay evidence-gated: Tizen reports no DTS decode, and TrueHD in MP4
  is unsupported essentially everywhere.

E-AC-3 is never an encode target

  Tizen accepts E-AC-3 for direct play but not for transcode. A source
  E-AC-3 track still passes through untouched via the copy path, which is
  that direct-play route, but an eac3 *target* now emits AC-3 instead: same
  channel layout, broader hardware decode support, and no risk of silent
  audio on the devices that asked for surround.

Two of my own tests from #148/#149 asserted the over-restrictive behavior
and were recalibrated rather than worked around, with DTS standing in for
the fragile set.
@cursor

cursor Bot commented Jul 30, 2026

Copy link
Copy Markdown

Bugbot is not enabled for your account, so this pull request was not reviewed.

Enable Bugbot in the Cursor dashboard to get automatic reviews on future PRs.

@coderabbitai

coderabbitai Bot commented Jul 30, 2026 •

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@JonahMMay, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 30 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: dd01f4f4-4570-4510-993c-69bc8d2441d2

📥 Commits

Reviewing files that changed from the base of the PR and between 1b9de34 and a962fd7.

📒 Files selected for processing (7)
  • internal/api/handlers/playback.go
  • internal/api/handlers/playback_v3.go
  • internal/playback/audio_channels.go
  • internal/playback/audio_channels_test.go
  • internal/playback/transcode.go
  • internal/playback/transcode_hevc_tag_test.go
  • internal/transcodenode/server.go
📝 Walkthrough

Walkthrough

Playback now selects client-decodable audio tracks when permitted, propagates updated track indices through playback resolution, refines remux safety by codec family, and encodes E-AC-3 targets as AC-3.

Changes

Audio playback compatibility

Layer / File(s) Summary
Client-playable audio track selection and propagation
internal/playback/audio_select.go, internal/playback/audio_select_internal_test.go, internal/api/handlers/playback.go
Adds capability-aware track ranking and carries the potentially remapped audio track index through playback resolution, alternate-file selection, and legacy startup.
Remux audio safety rules
internal/playback/resolver.go, internal/playback/resolver_test.go, internal/playback/audio_select_internal_test.go
Allows AC-3 family copying with decoder or passthrough claims while requiring passthrough evidence for DTS and TrueHD.
Audio transcode target handling
internal/playback/transcode.go, internal/playback/transcode_hevc_tag_test.go
Routes E-AC-3 and AC-3 targets through AC-3 encoding and verifies E-AC-3 source copying remains supported.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant PlaybackHandler
  participant SelectClientPlayableAudioTrack
  participant PlaybackResolver
  Client->>PlaybackHandler: request playback with capabilities
  PlaybackHandler->>SelectClientPlayableAudioTrack: provide audio tracks and codec claims
  SelectClientPlayableAudioTrack-->>PlaybackHandler: return selected audio track index
  PlaybackHandler->>PlaybackResolver: resolve playback method and audio handling
  PlaybackResolver-->>PlaybackHandler: return remux or transcode decision
  PlaybackHandler-->>Client: start playback with resolved audio selection
Loading

Possibly related PRs

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 75.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main change: preferring a playable existing audio track over re-encoding an incompatible one.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/select-playable-audio-track

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Nitpick comments (2)
internal/playback/audio_select.go (1)

260-261: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Local langMatch shadows the package-level langMatch function.

langMatch := preferredLang == "" || track.Language == "" || langMatch(track.Language, preferredLang) declares a local bool that shadows func langMatch (line 24). This compiles correctly — Go's short-var-decl scoping means the RHS call still resolves to the outer function — but it's confusing on a re-read since the same identifier means two different things a few lines apart.

♻️ Suggested rename for clarity
-		langMatch := preferredLang == "" || track.Language == "" ||
+		langMatchesPreferred := preferredLang == "" || track.Language == "" ||
 			langMatch(track.Language, preferredLang)
 		if best < 0 ||
-			(langMatch && !bestLangMatch) ||
-			(langMatch == bestLangMatch && track.Channels > bestChannels) {
-			best, bestLangMatch, bestChannels = i, langMatch, track.Channels
+			(langMatchesPreferred && !bestLangMatch) ||
+			(langMatchesPreferred == bestLangMatch && track.Channels > bestChannels) {
+			best, bestLangMatch, bestChannels = i, langMatchesPreferred, track.Channels
 		}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/playback/audio_select.go` around lines 260 - 261, Rename the local
boolean declared in the track-selection logic to avoid shadowing the
package-level langMatch function, and update its uses in the surrounding
condition accordingly. Keep the function call resolving to the existing
package-level langMatch unchanged.
internal/api/handlers/playback.go (1)

1145-1166: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Dead store: selectedTrack reassigned at line 1163 but never read again.

After the reselection block updates selectedTrack = file.AudioTracks[idx], nothing downstream in the function reads selectedTrack again (only audioSupported/audioTrackIndex are used). Harmless today, but worth removing to avoid confusion or a future accidental reliance on a value that looks meaningful but isn't used.

♻️ Suggested cleanup
 		if idx, ok := playback.SelectClientPlayableAudioTrack(
 			file.AudioTracks, audioTrackIndex, req.CodecsAudio, req.MaxAudioChannels,
 		); ok {
 			audioTrackIndex = idx
-			selectedTrack = file.AudioTracks[idx]
 			audioSupported = true
 		}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/api/handlers/playback.go` around lines 1145 - 1166, Remove the dead
reassignment of selectedTrack inside the SelectClientPlayableAudioTrack success
branch. Keep updating audioTrackIndex and audioSupported as currently required,
and leave the initial selectedTrack assignment unchanged for the earlier
codec-support check.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@internal/api/handlers/playback.go`:
- Around line 1183-1188: Update the default branch of the playback
method-selection logic to return !audioSupported instead of the stale
transcodeAudio parameter, matching the PlayRemux branch after audio-track
reselection. Preserve the existing method and audioTrackIndex returns.

In `@internal/playback/transcode_hevc_tag_test.go`:
- Around line 116-128: Strengthen TestEAC3IsNeverAnEncodeTarget by asserting
that the AC-3 fallback also emits the intended supported channel limit for the
8-channel TrueHD fixture. If the limit is missing, update appendAudioArgs to add
the AC-3 channel cap while preserving the existing codec-selection assertions.

In `@internal/playback/transcode.go`:
- Around line 805-814: Cap the AC-3 fallback in the audio encoding branch of
internal/playback/transcode.go:805-814 to six channels using the existing
channel-handling convention, while preserving the AC-3 codec and bitrate. Update
the 8-channel case in internal/playback/transcode_hevc_tag_test.go:116-128 to
assert that the emitted ffmpeg arguments include this six-channel cap.

---

Nitpick comments:
In `@internal/api/handlers/playback.go`:
- Around line 1145-1166: Remove the dead reassignment of selectedTrack inside
the SelectClientPlayableAudioTrack success branch. Keep updating audioTrackIndex
and audioSupported as currently required, and leave the initial selectedTrack
assignment unchanged for the earlier codec-support check.

In `@internal/playback/audio_select.go`:
- Around line 260-261: Rename the local boolean declared in the track-selection
logic to avoid shadowing the package-level langMatch function, and update its
uses in the surrounding condition accordingly. Keep the function call resolving
to the existing package-level langMatch unchanged.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 3f5e2a43-80d5-42de-974c-5f29943f7d28

📥 Commits

Reviewing files that changed from the base of the PR and between 20cd636 and 76e3845.

📒 Files selected for processing (7)
  • internal/api/handlers/playback.go
  • internal/playback/audio_select.go
  • internal/playback/audio_select_internal_test.go
  • internal/playback/resolver.go
  • internal/playback/resolver_test.go
  • internal/playback/transcode.go
  • internal/playback/transcode_hevc_tag_test.go

Comment thread internal/api/handlers/playback.go Resolved
Comment thread internal/playback/transcode.go Resolved
JonahMMay and others added 2 commits July 30, 2026 03:54
selectedTrack was only ever read for the codec-support check that runs
before the re-selection block, so reassigning it after switching tracks
was dead -- golangci-lint's wastedassign caught it. Collapse the variable
into the one call that uses it.

No behavior change: audioTrackIndex and audioSupported already carry the
re-selection result into the switch below.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
…hannels

Two related channel-layout bugs on the audio encode path.

SourceAudioChannels was declared on TranscodeOpts and read by
EffectiveAudioChannels, but never assigned anywhere in production code -- so it
was always 0. That silently disabled the "never exceed the source" rule: a
stereo track played by a client declaring max_audio_channels=6 was upmixed into
5.1 AAC, inventing four channels and spending bitrate to say nothing. It is now
threaded from the probed track on both the legacy and v3 transcode paths, local
and remote, with a matching additive field on the transcode-node request.

The AC-3 branch emitted "-c:a ac3 -b:a 448k" with no channel argument at all,
so it honored neither the source count nor the client's declared ceiling -- the
same max_audio_channels contract the AAC path implements. A device reporting a
stereo sink got 5.1, and a stereo source got a 448k bitstream sized for
surround. EffectiveAC3Channels now caps at the source, the client ceiling, and
the encoder's own limit, and the bitrate follows the layout.

That encoder limit is measured, not assumed: `ffmpeg -h encoder=ac3` in our own
image lists 5.1 as the widest supported layout, with no 6.1 or 7.1 mode. Worth
recording what does *not* happen -- an 8-channel input does not fail. FFmpeg's
filter-graph negotiation already downmixes it to 5.1(side) at 448k, verified by
encoding a synthetic 7.1 source and probing the result. The cap is still worth
stating explicitly, because relying on negotiation is relying on it staying put,
and negotiation cannot know the client's ceiling. Where we know enough to choose
the layout we choose it; where we do not, EffectiveAC3Channels returns 0 and
omits -ac so negotiation still handles it -- naming 5.1 on an unknown source
would upmix one that turns out to be stereo.

EffectiveAC3Channels deliberately does not reuse EffectiveAudioChannels: that
function's fragile-lossless rule collapses TrueHD to stereo, which is right for
AAC (the stall it guards is in the TrueHD->AAC path) and wrong here, where an
AC-3 target exists precisely to carry surround to a receiver.

Not addressed, and pre-existing: RecipeCard mirrors the byte-affecting
TranscodeOpts fields but carries neither source audio codec nor channel count,
so a session reconstructed after a restart loses both the layout decision and
the TrueHD stereo safety. Fixing it means either growing every segment JWT or
re-deriving from the media file; the deferred path keeps today's behavior
(channels 0 -> negotiation), so this change does not make it worse.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
@JonahMMay
JonahMMay merged commit 3b44741 into main Jul 30, 2026
16 checks passed
@JonahMMay
JonahMMay deleted the fix/select-playable-audio-track branch July 30, 2026 04:18
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant